"""
@Version: V1.0
@Author: wilson
@License: Apache Licence
@Contact: wevsmy@qq.com
@Site: http://wevsmy.cn
@Software: PyCharm
@File: change_clothes.py
@Time: 5/5 16:32
"""
import cv2, json, os, random, uuid
import numpy as np
from urllib import request
from PIL import Image


class BingWallpaper():
    """下载必应壁纸"""
    def __init__(self):
        self.filePath = r"data"
        self.hosts = "http://cn.bing.com"
        self.imgDate = ""
        self.imgUrl = ""
        self.imgFileName = "temp.jpg"

    def __get_json_data(self, idx = 0):
        # idx = 0是今天的，-1明天，1昨天
        json_url = self.hosts+"/HPImageArchive.aspx?format=js&n=1&idx={}".format(idx)
        try:
            data = request.urlopen(json_url).read().decode("utf-8")
            json_data = json.loads(data)
            self.imgDate = json_data["images"][0]["enddate"]
            self.imgUrl = self.hosts + json_data["images"][0]["url"]
            # self.imgFileName = self.imgDate+"_"+json_data["images"][0]["url"].split("/")[4]
        except Exception as f:
            print("get_json_data:",f)

    def __down_img(self):
        with request.urlopen(self.imgUrl) as f:
            data = f.read()
            with open(str(self.filePath+os.sep+self.imgFileName), mode="wb") as f:
                f.write(data)

    def save_img(self, idx = 0):
        self.__get_json_data(idx)
        self.__down_img()
        # print("{} download!".format(self.imgFileName))


def getBgImg():
    "随机截取背景图并处理"
    bg = Image.open("data/temp.jpg")
    w, h = bg.size
    bg_x = random.randint(0, w - 720)
    bg_y = random.randint(0, h - 712)
    box = (bg_x, bg_y, bg_x + 720, bg_y + 712)
    new = bg.crop(box)
    new.save("data/bg.jpg")


def addImg():
    "输出以时间戳命名的图片"
    fileName = str(uuid.uuid1()) + ".jpg"
    filePath = os.path.join("out", fileName)
    bg_img = cv2.imread('data/bg.jpg')
    base_img = cv2.imread("data/base.png")
    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([130, 255, 255])
    hsv = cv2.cvtColor(base_img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    new_img = cv2.bitwise_and(bg_img, bg_img, mask=mask)
    res = cv2.add(new_img, base_img)  # 进行融合
    cv2.imwrite(filePath, res)


def main():
    # 随机获取壁纸
    wall = BingWallpaper()
    wall.save_img(random.randint(1,7))
    # 随机截取部分做背景
    getBgImg()
    # 输出图片
    addImg()
    print("ojbk!")


if __name__ == '__main__':
    for i in range(10):
        main()

